#include "Textbox.h"

#define TEXTBOX_DEFAULT_WIDTH 20
#define TEXTBOX_DEFAULT_HEGHT 10

Textbox::Textbox(int posX, int posY, Widget *parent) :
WidgetClickeableWithText(std::string(STRING_EMPTY),Color::BLANCO,
		TEXTBOX_DEFAULT_WIDTH,TEXTBOX_DEFAULT_HEGHT,posX, posY, parent) {

	this->inputChanged = false;
	this->mousePressed = false;
	this->mouseIsOver = false;
	this->keyDown = false;
	this->isChar = false;
	this->backSpace = false;

	keyState = 0;
	keyPressed = false;

}

Textbox::~Textbox() {
}


void Textbox::handleEvent(Event event) {
	mousePressed = (event.getButtonState() == Pressed);
	mouseIsOver = isMouseOver(event);
	keyDown = (event.getType() == KeyPressed);
	isChar = ((event.getKeyUnicode() >= (Uint16) 32)
			&& (event.getKeyUnicode() <= (Uint16) 255));
	tempInput = (char) event.getKeyUnicode();
	backSpace = (event.getKey() == Backspace);

	keyState = event.getType();
}

void Textbox::resolve() {

	if (this->mousePressed && (!this->mouseIsOver) && this->pressed) {
		pressed = false;
	} else if (this->mousePressed && this->mouseIsOver) {
		pressed = true;
	}

	if (this->pressed && keyState == KeyPressed) {
		keyPressed = true;
		if (isChar || backSpace) {
			inputChanged = true;
			letra = tempInput;
		}
	}
	if (this->pressed && keyState == KeyReleased && keyPressed) {
		keyPressed = false;

		if (inputChanged) {
			if (backSpace) {
				if (this->text.length() > 0) {
					this->text.erase(this->text.length() - 1);
				}else {
					inputChanged = false;
				}

			} else {
				this->text += letra;
			}
		}
	}


}

std::string Textbox::getInput() {
	return this->text;
}
